package com.hyz.yuaiagent.app;

import com.hyz.yuaiagent.advisor.LoveAppRagCustomAdvisorFactory;
import com.hyz.yuaiagent.advisor.MyLoggerAdvisor;
import com.hyz.yuaiagent.rag.query.MyQueryRewriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveAppDemoWithRetrievalAugmentationAdvisor {

    public static final String SysPrompt = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；恋爱状态询问沟通、" +
            "习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案";
    private final MyQueryRewriter myQueryRewriter;
    private final ChatClient chatClient;


    @Autowired
    public LoveAppDemoWithRetrievalAugmentationAdvisor(MyQueryRewriter myQueryRewriter,
                                                       ChatModel dascopeChatModel,
                                                       @Qualifier("loveAppVectorStore") VectorStore loveAppVectorStore) {
        this.myQueryRewriter = myQueryRewriter;
        this.chatClient = ChatClient.builder(dascopeChatModel)
                .defaultSystem(SysPrompt)
                .defaultAdvisors(
                        LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore, "单身")
                )
                .defaultAdvisors(new MyLoggerAdvisor())
                .build();
    }


    public void doChat(String msg, String id) {
        String rewrite = myQueryRewriter.doQueryRewrite(msg);
        ChatResponse chatResponse = chatClient.prompt()
                .user(rewrite)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, id)
//                         来自上下文的聊天内存响应大小 如果为1 就是只能记忆1轮对话
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String string = chatResponse.getResult().getOutput().getText().toString();

        log.info(string);

    }
}
